package com.xiaoyu.client.ui.activity.main.mine.wallet_and_member;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.pm.PackageManager;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.RadioGroup;

import com.alipay.sdk.app.PayTask;
import com.xiaoyu.client.R;
import com.xiaoyu.client.model.PayResult;
import com.xiaoyu.client.network.NetworkManager;
import com.xiaoyu.client.ui.activity.mall.OrderComfirmActivity;
import com.xiaoyu.commonlib.network.CommonHttpResponser;
import com.xiaoyu.commonlib.ui.base.BaseActivityWithTitle;
import com.xiaoyu.commonlib.utils.PreferencesUtil;
import com.xiaoyu.commonlib.utils.ToastUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * @author jx
 * @date 创建时间 2018/10/12
 * @Description 我的 -- 我的钱包 -- 充值
 */
public class TopUpActivity extends BaseActivityWithTitle implements RadioGroup.OnCheckedChangeListener {
    private static final int SDK_PAY_FLAG = 1;
    private View mView;
    @BindView(R.id.activity_pay_way_group)
    RadioGroup radioGroup;
    @BindView(R.id.activity_top_up_money)
    EditText mMoney;

    @Override
    protected void loadContentView(ViewGroup parent) {
        setTitleText("余额充值");
        requestPermission();
        mView = LayoutInflater.from(this).inflate(R.layout.activity_top_up, parent, true);
        ButterKnife.bind(this);
        radioGroup.setOnCheckedChangeListener(this);
    }

    @Override
    public void onCheckedChanged(RadioGroup radioGroup, int i) {
        switch (radioGroup.getCheckedRadioButtonId()) {
            case R.id.activity_pay_way_alipay_btn:
                if (TextUtils.isEmpty(mMoney.getText().toString())) {
                    ToastUtil.showToast(TopUpActivity.this, "请输入金额");
                    return;
                }
                commitOrder("ali");
                break;
            case R.id.activity_pay_way_wechat_btn:
                ToastUtil.showToast(this, "暂未开通微信支付");
                commitOrder("wx");
                break;
        }
    }

    /**
     * 提交订单
     */
    private void commitOrder(final String payWay) {
        NetworkManager.balanceTopup(PreferencesUtil.getString(PreferencesUtil.TOKEN, ""), mMoney.getText().toString(), payWay, new CommonHttpResponser() {
            @Override
            public void onSuccess(String result) {
                String orderInfo = null;
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    orderInfo = jsonObject.getString("data");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                if (payWay.equals("wx")) {//微信支付

                }
                if (payWay.equals("ali")) {//支付宝支付
                    toAliPay(orderInfo);
                }
            }

            @Override
            public void onFailed(String errorCode, String errorDiscription) {
            }
        });
    }

    /**
     * 支付(支付宝)
     */
    private void toAliPay(final String orderInfo) {
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask(TopUpActivity.this);
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG:
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知
                     */
                    String resultInfo = payResult.getResult();//同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    //判断resultStatus，为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        //该笔订单是否真实支付成功，需要依赖服务端的异步通知
                        ToastUtil.showToast(TopUpActivity.this, "支付成功");
                        finish();
                    } else {
                        //该笔订单真实的支付结果，需要依赖服务端的异步通知
                        ToastUtil.showToast(TopUpActivity.this, "支付失败");
                        finish();
                    }
            }
        }
    };


    /**
     * 检查支付宝 SDK 所需的权限，并在必要的时候动态获取。
     * 在 targetSDK = 23 以上，READ_PHONE_STATE 和 WRITE_EXTERNAL_STORAGE 权限需要应用在运行时获取。
     * 如果接入支付宝 SDK 的应用 targetSdk 在 23 以下，可以省略这个步骤。
     */
    private void requestPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE)
                != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {

            ActivityCompat.requestPermissions(this,
                    new String[]{
                            Manifest.permission.READ_PHONE_STATE,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE
                    }, 123);
        }
    }

    /**
     * 权限获取回调
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case 123: {

                // 用户取消了权限弹窗
                if (grantResults.length == 0) {

                    return;
                }

                // 用户拒绝了某些权限
                for (int x : grantResults) {
                    if (x == PackageManager.PERMISSION_DENIED) {
                        return;
                    }
                }

                // 所需的权限均正常获取
            }
        }
    }

}
